package com.shaokel.pojo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author 少丶客
 * @ClassName Blog
 * @Description TODO
 * @Date 2020/6/23 17:15
 * @Vesion 1.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity //查找对应的sql表
@Table(name="t_blog")//创建表
public class Blog {

    @Id
    @GeneratedValue
    private Long id;                    //id
    private String title;               //标题

    @Basic(fetch= FetchType.LAZY)
    @Lob
    private String content;             //内容
    private String firstPicture;        //首图
    private String flag;                //标记
    private Integer views;              //浏览次数
    private boolean appreciation;       //赞赏开启
    private boolean shareStatement;     //版权开启
    private boolean commentabled;    //评论开启
    private boolean published;       //发布
    private boolean recommend;          //推荐
    private String description;
    @Temporal(TemporalType.TIMESTAMP)
    private Date createTime;            //创建时间
    @Temporal(TemporalType.TIMESTAMP)
    private Date updateTime;            //更新时间

    @ManyToOne      //多对一     blog-->type    blog是维护端
    private Type type;

    @ManyToMany(cascade = {CascadeType.PERSIST})     //多对多          blog维护端      CascadeType.PERSIST级联保存
    private List<Tag> tags = new ArrayList<>();

    @ManyToOne      //多对一    blog-->user   blog是维护端
    private User user;

    @OneToMany(mappedBy = "blog")       //一对多    blog-->comments   blog是被维护端
    private List<Comment> comments = new ArrayList<>();

    @Transient      //该属性不会被映射进数据库
    private String tagIds;

    public void init(){
        this.tagIds = tagsToIds(this.getTags());
    }

    private String tagsToIds(List<Tag> tags){
        if(!tags.isEmpty()){
            StringBuffer ids = new StringBuffer();
            boolean flag = false;
            for (Tag tag : tags) {
                if(flag){
                    ids.append(",");
                }else{
                    flag = true;
                }
                ids.append(tag.getId());
            }
            return ids.toString();
        }
        return tagIds;
    }

}